package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dto.CategoryDTO;
import com.example.mapper.CategoryMapper;
import com.example.pojo.Category;
import com.example.pojo.PageBean;
import com.example.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;


@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {


    //实现事务传递
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public Category findByName(String name) {
        //构造查询条件
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<Category>()
                .eq(name != null && name != "", Category::getName, name);
        return getOne(wrapper);
    }

    //实现事务传递
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void updateByName(String name, Integer newSum) {
        //构造更新条件
        LambdaUpdateWrapper<Category> wrapper = new LambdaUpdateWrapper<Category>()
                .eq(name != null && name != "", Category::getName, name)
                .set(newSum != null, Category::getSum, newSum)
                .set(Category::getUpdateTime, LocalDateTime.now());
        update(wrapper);
    }

    //实现事务传递
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void deleteByName(String name) {
        //构造删除条件
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<Category>()
                .eq(name != null && name != "", Category::getName, name);
        remove(wrapper);
    }

    @Override
    public PageBean<Category> find(CategoryDTO categoryDTO) {
        //1.分页参数
        Page<Category> p = Page.of(categoryDTO.getPage(), categoryDTO.getPageSize());

        //2.排序条件
        p.addOrder(new OrderItem("update_time", false));

        //3.查询
        page(p);

        //封装结果并返回
        return PageBean.of(p.getTotal(), p.getRecords());
    }
}
